using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SqlSugar;

namespace Admin.NET.Application.SqlSugarTD;

public static class SqlSugarTDPortion
{
	public static int InsertTableTD<T>(this SqlSugarClient client, T model) where T : class, new()
	{
		Type type = typeof(T);
		List<PropertyInfo> tagProperties = (from u in type.GetProperties()
			where u.CustomAttributes.Any((CustomAttributeData s) => s.AttributeType == typeof(TDTag))
			select u).ToList();
		string sql = client.Insertable(model).ToSqlString();
		Dictionary<string, string> dicTag = new Dictionary<string, string>();
		foreach (PropertyInfo property in tagProperties)
		{
			dicTag.Add(property.Name, property.GetValue(model).ToString());
		}
		string tableName = "INTO `" + type.Name + "`";
		string tagName = string.Join(",", dicTag.Keys.ToArray()) ?? "";
		string tagValue = string.Join("','", dicTag.Values.ToArray()) ?? "";
		string newTableName = $"{tableName}{string.Join("", dicTag.Values.ToArray())} USING {type.Name} ({tagName}) Tags('{tagValue}')";
		sql = sql.Replace(tableName, newTableName).Replace("`", "").Replace("N'", "'");
		return client.Ado.ExecuteCommand(sql);
	}
}
